package com.sjgs.gis.fsrest.handler;

import com.sjgs.gis.errors.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.dao.NonTransientDataAccessResourceException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.zalando.problem.Status;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * @classDesc: 统一异常处理
 * @author: chenggang
 * @createTime: 2018/10/30
 */

public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    private static final Log log = LogFactory.getLog(GlobalExceptionHandler.class);

    /**
     * MessageReader
     */
    private List<HttpMessageReader<?>> messageReaders = Collections.emptyList();

    /**
     * MessageWriter
     */
    private List<HttpMessageWriter<?>> messageWriters = Collections.emptyList();

    /**
     * ViewResolvers
     */
    private List<ViewResolver> viewResolvers = Collections.emptyList();

    /**
     * 存储处理异常后的信息
     */
    private ThreadLocal<Map<String, Object>> exceptionHandlerResult = new ThreadLocal<>();

    /**
     * 参考AbstractErrorWebExceptionHandler
     *
     * @param messageReaders
     */
    public void setMessageReaders(List<HttpMessageReader<?>> messageReaders) {
        Assert.notNull(messageReaders, "'messageReaders' must not be null");
        this.messageReaders = messageReaders;
    }

    /**
     * 参考AbstractErrorWebExceptionHandler
     *
     * @param viewResolvers
     */
    public void setViewResolvers(List<ViewResolver> viewResolvers) {
        this.viewResolvers = viewResolvers;
    }

    /**
     * 参考AbstractErrorWebExceptionHandler
     *
     * @param messageWriters
     */
    public void setMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
        Assert.notNull(messageWriters, "'messageWriters' must not be null");
        this.messageWriters = messageWriters;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable error) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        if (error instanceof GridFSIOException) {
            errorAttributes.put("status", ((GridFSIOException) error).getStatus());
            errorAttributes.put("type", ((GridFSIOException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        } else if (error instanceof HDFSIOException) {
            errorAttributes.put("status", ((HDFSIOException) error).getStatus());
            errorAttributes.put("type", ((HDFSIOException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        } else if (error instanceof LocalFileIOException) {
            errorAttributes.put("status", ((LocalFileIOException) error).getStatus());
            errorAttributes.put("type", ((LocalFileIOException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        } else if (error instanceof DataBaseConnectException) {
            errorAttributes.put("status", ((DataBaseConnectException) error).getStatus());
            errorAttributes.put("type", ((DataBaseConnectException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        } else if (error instanceof InvalidChunkException) {
            errorAttributes.put("status", ((InvalidChunkException) error).getStatus());
            errorAttributes.put("type", ((InvalidChunkException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        } else if (error instanceof BadRequestAlertException) {
            errorAttributes.put("status", ((BadRequestAlertException) error).getStatus());
            errorAttributes.put("type", ((BadRequestAlertException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        } else if (error instanceof InvalidBufferException) {
            errorAttributes.put("status", ((InvalidBufferException) error).getStatus());
            errorAttributes.put("type", ((InvalidBufferException) error).getType().getPath());
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        }else if(error instanceof NonTransientDataAccessResourceException){
            errorAttributes.put("status", Status.BAD_REQUEST);
            errorAttributes.put("type", ErrorConstants.INVALID_CONNECT_URL);
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        }else {
            errorAttributes.put("status", Status.INTERNAL_SERVER_ERROR);
            errorAttributes.put("timestamp", new Date());
            errorAttributes.put("path", exchange.getRequest().getPath().value());
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("requestId", exchange.getRequest().getId());
        }

        /**
         * 参考AbstractErrorWebExceptionHandler
         */
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(error);
        }
        exceptionHandlerResult.set(errorAttributes);
        ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
        return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse)
                .route(newRequest)
                .switchIfEmpty(Mono.error(error))
                .flatMap((handler) -> handler.handle(newRequest))
                .flatMap((response) -> write(exchange, response));

    }

    /**
     * 参考DefaultErrorWebExceptionHandler
     *
     * @param request
     * @return
     */
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Map<String, Object> errorPropertiesMap = exceptionHandlerResult.get();
        int statusCode = ((Status) errorPropertiesMap.get("status")).getStatusCode();
        return ServerResponse.status(HttpStatus.valueOf(statusCode))
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(errorPropertiesMap));
    }

    /**
     * 参考AbstractErrorWebExceptionHandler
     *
     * @param exchange
     * @param response
     * @return
     */
    private Mono<? extends Void> write(ServerWebExchange exchange,
                                       ServerResponse response) {
        exchange.getResponse().getHeaders()
                .setContentType(response.headers().getContentType());
        return response.writeTo(exchange, new ResponseContext());
    }

    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    private class ResponseContext implements ServerResponse.Context {

        @Override
        public List<HttpMessageWriter<?>> messageWriters() {
            return GlobalExceptionHandler.this.messageWriters;
        }

        @Override
        public List<ViewResolver> viewResolvers() {
            return GlobalExceptionHandler.this.viewResolvers;
        }

    }
}